package com.drinks.yiniang.ui.activity.user.login;

import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.drinks.yiniang.R;
import com.drinks.yiniang.common.help.QuickLoginHelp;
import com.drinks.yiniang.common.help.UserTokenSingleton;
import com.drinks.yiniang.entity.event.WXLoginEvent;
import com.drinks.yiniang.entity.user.LoginJson;
import com.drinks.yiniang.io.api.CommonApiIO;
import com.drinks.yiniang.io.api.LoginApiIO;
import com.drinks.yiniang.ui.activity.MainActivity;
import com.drinks.yiniang.utils.SharedPreUtils;
import com.drinks.yiniang.utils.ToastUtils;
import com.hansen.library.Constants;
import com.drinks.yiniang.ui.activity.common.WebActivity;
import com.hansen.library.entity.BaseJson;
import com.hansen.library.io.tuple.Tuple2;
import com.hansen.library.listener.APIRequestCallback;
import com.hansen.library.ui.widget.textview.ClearEditText;
import com.hansen.library.ui.activity.BaseTranBarActivity;
import com.hansen.library.utils.StringUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * 登录页面
 *
 * @author han
 * @date 2019/09/03
 */
public class LoginActivity extends BaseTranBarActivity {

    public static boolean isActive;

    private final int REQ_TO_NEXT_PAGE_CODE = 0x01;

    //返回
    private ImageView iv_login_back;
    //微信登录
    private ImageView iv_login_by_wechat;
    //支付宝账号登录
    private ImageView iv_login_by_ali;
    //微博登录
    private ImageView iv_login_by_weibo;
    //国际区号
    private TextView tv_login_country_code;
    //协议
    private TextView tv_login_register_agreement;
    //登录账号
    private ClearEditText et_login_account;
    //获取验证码
    private Button btn_login_get_code;

    private QuickLoginHelp mQuickLoginHelp;

    @Override
    protected void initView() {
        iv_login_back = findViewById(R.id.iv_login_back);
        iv_login_by_wechat = findViewById(R.id.iv_login_by_wechat);
        iv_login_by_ali = findViewById(R.id.iv_login_by_ali);
        iv_login_by_weibo = findViewById(R.id.iv_login_by_weibo);

        tv_login_country_code = findViewById(R.id.tv_login_country_code);
        tv_login_register_agreement = findViewById(R.id.tv_login_register_agreement);

        et_login_account = findViewById(R.id.et_login_account);

        btn_login_get_code = findViewById(R.id.btn_login_get_code);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        mContext = this;
        isActive = true;

        setTextClickData();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        isActive = true;
    }

    @Override
    protected void initListener() {
        iv_login_back.setOnClickListener(this);
        iv_login_by_wechat.setOnClickListener(this);
        iv_login_by_ali.setOnClickListener(this);
        iv_login_by_weibo.setOnClickListener(this);
        tv_login_country_code.setOnClickListener(this);
        btn_login_get_code.setOnClickListener(this);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void widgetClick(View v) {
        switch (v.getId()) {
            case R.id.iv_login_back://返回
                finish();
                break;
            case R.id.tv_login_country_code://选择国际区号

                break;
            case R.id.iv_login_by_wechat://微信登录
                if (mQuickLoginHelp == null) {
                    mQuickLoginHelp = new QuickLoginHelp(this);
                }
                mQuickLoginHelp.doWxAuthLogin();
                break;
            case R.id.iv_login_by_ali://支付宝登录

                break;
            case R.id.iv_login_by_weibo://微博登录

                break;
            case R.id.btn_login_get_code://获取验证码
                doGetVerificationCode();
                break;
            default:
                break;
        }
    }

    @Override
    public int getTranBarResID() {
        return R.layout.activity_login;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Constants.RESULT_CODE_NORMAL && requestCode == REQ_TO_NEXT_PAGE_CODE) {
            setResult(Constants.RESULT_CODE_NORMAL);
            finish();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(WXLoginEvent event) {
        if (event != null && event.getCode() != null) {
            doWeiXinLogin(event.getCode());
        } else {
            ToastUtils.showShort(getString(R.string.text_auth_fail));
        }
    }

    private void doGetVerificationCode() {
        final String mobile = StringUtils.getEditTextString(et_login_account.getEditableText());

        if (StringUtils.isEmpty(mobile)) {
            ToastUtils.showShort(getString(R.string.text_hint_input_phone_num));
            return;
        }

        if (!StringUtils.isPhone(mobile)) {
            ToastUtils.showShort(getString(R.string.text_hint_input_true_phone_num));
            return;
        }

        showLoadingDialog();

        CommonApiIO.getInstance().getSmsCode(mobile, new APIRequestCallback<BaseJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(BaseJson res) {
                Intent intent = new Intent(mContext, VerificationCodeActivity.class);
                intent.putExtra(Constants.KeyMobile, mobile);
                startActivityForResult(intent, REQ_TO_NEXT_PAGE_CODE);
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    //微信授权登录
    private void doWeiXinLogin(String code) {
        showLoadingDialog(R.string.text_login_loading);

        LoginApiIO.getInstance().doWxAuthLogin(code, new APIRequestCallback<LoginJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(LoginJson res) {
                boolean isExistPhone = !StringUtils.isEmpty(res.getData().getUser().getMobile());

                if(isExistPhone) {//手机号已存在，无需绑定
                    SharedPreUtils.getInstance().saveUserToken(res.getData().getAccess_token());
                    SharedPreUtils.getInstance().saveUserID(res.getData().getUser().getId());
                    SharedPreUtils.getInstance().saveIsOpenPayPasswordID(Constants.STATUS_GLOBAL_YES.equals(res.getData().getUser().getOpen_pay()) ? Constants.STATUS_GLOBAL_YES : Constants.STATUS_GLOBAL_NO);

                    setResult(Constants.RESULT_CODE_NORMAL);
                    finish();
                } else {
                    UserTokenSingleton.getInstance().setGlobalUserToken(res.getData().getAccess_token());

                    Intent mIntent = new Intent(mContext, BindPhoneActivity.class);
                    startActivityForResult(mIntent, REQ_TO_NEXT_PAGE_CODE);
                }
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    private void setTextClickData() {
        SpannableString spanns = new SpannableString(getString(R.string.text_read_and_agree_register_agreement));

        if (spanns.length() < 13) {
            return;
        }

        spanns.setSpan(new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                Intent intent = new Intent(mContext, WebActivity.class);
                intent.putExtra(Constants.KeyType, WebActivity.WEB_TYPE_REGISTER_AGREEMENT);
                startActivity(intent);
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                /**set textColor**/
                ds.setColor(ContextCompat.getColor(mContext, R.color.color_3d6bd8));
                /**Remove the underline**/
                ds.setUnderlineText(false);
            }
        }, 12, spanns.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

        tv_login_register_agreement.setHighlightColor(Color.TRANSPARENT);
        tv_login_register_agreement.setMovementMethod(LinkMovementMethod.getInstance());
        tv_login_register_agreement.setText(spanns);
    }

    @Override
    protected void onDestroy() {
        isActive = false;

        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        if (mQuickLoginHelp != null) {
            mQuickLoginHelp.releaseResource();
        }
        super.onDestroy();
    }
}
